package quick.start.core.view;

import java.util.ArrayList;

import android.os.Bundle;

import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.requestmanager.RequestManager;

public class RequestProxy implements RequestManager.RequestListener {

	private static final String SAVED_STATE_REQUEST_LIST = "savedStateRequestList";
	
	protected RequestManager mRequestManager;
	protected ArrayList<Request> mRequestList;
	protected RequestResultListener mResultListener;
	
	public RequestProxy(RequestManager manager, RequestResultListener listener){
		mRequestManager = manager;
		mResultListener = listener;
	}
	
	public void saveInstanceState(Bundle bundle){
		bundle.putParcelableArrayList(SAVED_STATE_REQUEST_LIST, mRequestList);
	}

	public void loadInstanceState(Bundle bundle){
		if(null != bundle){
			mRequestList = bundle.getParcelableArrayList(SAVED_STATE_REQUEST_LIST);
		}else{
			mRequestList = new ArrayList<Request>();
		}
	}
	
	public void loadRequestList(){
		for (int i = 0; i < mRequestList.size(); i++) {
			Request request = mRequestList.get(i);
			if(mRequestManager.isRequestInProgress(request)){
				mRequestManager.addRequestListener(this, request);
			}else{
				if(request.isMemoryCacheEnabled()){
					mRequestManager.callListenerWithCachedData(this, request);
				}
				mRequestList.remove(request);
				i--;
			}
		}
	}
	
	public void removeRequestListener(){
		if(!mRequestList.isEmpty()){
			mRequestManager.removeRequestListener(this);
		}
	}
	
	public void sendRequest(Request request){
		mRequestManager.execute(request, this);
		mRequestList.add(request);
	}
	
	@Override
	public void onRequestConnectionError(Request request, int statusCode) {
        if (mRequestList.contains(request)) {
            mRequestList.remove(request);
            mResultListener.beforeRequestEnd(request);
            if (mResultListener != null) {
                mResultListener.onRequestFailure(request, null);
            }
        }
	}

	@Override
	public void onRequestCustomError(Request request, Bundle resultData) {
        if (mRequestList.contains(request)) {
            mRequestList.remove(request);
            mResultListener.beforeRequestEnd(request);
            if (mResultListener != null) {
                mResultListener.onRequestFailure(request, resultData);
            }
        }
	}

	@Override
	public void onRequestDataError(Request request) {
        if (mRequestList.contains(request)) {
            mRequestList.remove(request);
            mResultListener.beforeRequestEnd(request);
            if (mResultListener != null) {
                mResultListener.onRequestFailure(request, null);
            }
        }	
	}

	@Override
	public void onRequestFinished(Request request, Bundle resultData) {
		if(mRequestList.contains(request)){
			mRequestList.remove(request);
			mResultListener.beforeRequestEnd(request);
			if(mResultListener != null){
				mResultListener.onRequestSuccess(request, resultData);
			}
		}
	}
}
